﻿
using System.Drawing;
using System.Windows.Forms;

namespace CatEars.Core.UI.Controls.Forms
{
    /// <summary>
    /// 用于加载UserControl的基础窗口
    /// </summary>
    public class FrmCtlLoader : Form
    {
        /// <summary>
        /// 子类窗体宽度偏移 子类有尺寸偏移则重写该属性
        /// </summary>
        protected virtual int WidthOffset
        {
            get { return 0; }
        }
        /// <summary>
        /// 子类窗体高度偏移 子类有尺寸偏移则重写该属性
        /// </summary>
        protected virtual int HeightOffset
        {
            get { return 0; }
        }

        /// <summary>
        /// 默认构造函数 用于VS设计 或子类实例化
        /// </summary>
        protected FrmCtlLoader() { }

        /// <summary>
        /// 标记是否已经设置了UserControl
        /// UserControl只允许设置一次
        /// </summary>
        private bool m_ctlSetted = false;

        /// <summary>
        /// 构造函数 根据UserControl设定窗口大小等
        /// </summary>
        /// <param name="ctl">UserControl对象</param>
        public FrmCtlLoader(Control ctl)
        {
            this.SetUserControl(this, ctl);

            //窗体参数设置
            string strText = ctl.Tag as string;
            if (strText != null)
            {
                this.Name = strText;
                this.Text = strText;
            }
            else
            {
                this.Name = ctl.GetType().ToString();
                this.Text = ctl.GetType().ToString();
            }
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        /// <summary>
        /// 加载UserControl到界面 根据UserControl设定窗口大小等
        /// 不将SetUserControl内容防止到构造函数中，方便子类使用
        /// UserControl只允许设置一次
        /// </summary>
        /// <param name="container">容器控件</param>
        /// <param name="ctl">用户控件</param>
        protected void SetUserControl(Control container, Control ctl)
        {
            if (m_ctlSetted)
            {
                return;
            }
            this.SuspendLayout();
            container.SuspendLayout();
            ctl.Dock = DockStyle.Fill;
            container.Controls.Add(ctl);
            container.ResumeLayout();

            //根据内部控件大小调整窗体大小
            this.ClientSize = new Size(
                ctl.ClientSize.Width + WidthOffset,
                ctl.ClientSize.Height + HeightOffset);
            int intWidthOffset = this.Size.Width - ctl.ClientSize.Width;//16
            int intHeightOffset = this.Size.Height - ctl.ClientSize.Height;//38
            if (!ctl.MaximumSize.IsEmpty)
            {
                this.MaximumSize = new Size(
                    ctl.MaximumSize.Width + intWidthOffset,
                    ctl.MaximumSize.Height + intHeightOffset);
            }
            if (!ctl.MinimumSize.IsEmpty)
            {
                this.MinimumSize = new Size(
                    ctl.MinimumSize.Width + intWidthOffset,
                    ctl.MinimumSize.Height + intHeightOffset);
            }

            this.ResumeLayout();

            m_ctlSetted = true;
        }
    }
}
